package com.youlai.boot.factory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.factory.mapper.SalaryPaymentRecordMapper;
import com.youlai.boot.factory.model.entity.SalaryPaymentRecord;
import com.youlai.boot.factory.service.SalaryPaymentRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 工资发放记录 Service 实现
 *
 * @author youlaitech
 * @since 2025-10-29
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SalaryPaymentRecordServiceImpl extends ServiceImpl<SalaryPaymentRecordMapper, SalaryPaymentRecord>
        implements SalaryPaymentRecordService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean paySalary(List<Long> employeeIds, String paymentMonth) {
        List<SalaryPaymentRecord> recordsToInsert = new ArrayList<>();
        
        for (Long employeeId : employeeIds) {
            // 检查是否已经发放过工资
            LambdaQueryWrapper<SalaryPaymentRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SalaryPaymentRecord::getEmployeeId, employeeId)
                       .eq(SalaryPaymentRecord::getPaymentMonth, paymentMonth);
            
            long count = this.count(queryWrapper);
            if (count > 0) {
                log.warn("员工ID: {} 在月份: {} 已经发放过工资，跳过", employeeId, paymentMonth);
                continue;
            }
            
            // 创建发放记录
            SalaryPaymentRecord record = new SalaryPaymentRecord();
            record.setEmployeeId(employeeId);
            record.setPaymentMonth(paymentMonth);
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            
            recordsToInsert.add(record);
        }
        
        if (recordsToInsert.isEmpty()) {
            log.info("所有员工都已发放过工资，无需重复发放");
            return true;
        }
        
        // 批量插入
        return this.saveBatch(recordsToInsert);
    }
}
